var tool = {
    empty: function(){},
    jsonDecode: function(data){
        return eval('(' + data + ')');
    },
    post: function(a, form){
        $.ajax({
            url: form ? form.attr('action') : a.url,
            type: 'post',
            data: (form ? form.serialize() : a.data) + '&js=1',
            dataType: a.type ? a.type : 'json',
            success: a.onComplete|| function(){}
        });
    },
    form: function (custom,initiation,complete){
        //custom form element
        if(custom){
            $('a.checkboxItem').each(function(){
                $(this).bind({
                    'keydown':function(e){
                        if(e.keyCode == 32) tool.checkbox($(this));
                    },
                    'click':function(){
                        tool.checkbox($(this));
                    }
                });
                if($('#'+$(this).attr('title')).val() > 0)
                    $(this).addClass('checked');
            });
        }
        $('#form').bind('submit', function(e) {
            e.preventDefault();
            //$('submit').set('disabled','disabled');
            $('#result').empty();
            $('div.marked').removeClass('marked');
            $('#loader').css('display','inline');
            if(initiation) initiation();
            tool.post({
                'onComplete':function(r){
                    if(r){
                        if(r.code == 200 && complete) _complete(r.message);
                        else tool.result(r.code,r.status,r.message,r.fields,r.redirect,r.debug);
                    }
                }
            },$(this));
        });
    },
    linkposts: function (){
        console.log($('a.linkpost'));
        $('a.linkpost').each(function(){
            var link =  $(this).attr('href').split('?');
            $(this).attr('href','javascript:tool.empty();');
            $(this).click(function(e){
                e.preventDefault();
                tool.linkpost($(this),link[0],link[1]);
            });
        });
    },
    linkpost: function (el, link, data){
        el.attr('disabled','disabled');
        $('#result').empty();
        el.addClass('loader');
        var func = 'tool.post({\'url\':\''+link+'\',\'data\':\''+data+'\',\'onComplete\':function(result){if(result)tool.result(result.code,result.status,result.message,result.fields,result.redirect,result.debug)}});';
        tool.confirm('header', el.attr('title'), func);
    },
    remove: function (el, link, data){
        $(el).attr('disabled','disabled');
        $('#result').empty();
        $(el).addClass('loader');
        var complete = function(r){
            if(r)if(r.code == 200) $('#'+r.message).fadeOut(); else tool.result(r.code,r.status,r.message,r.fields,r.redirect,r.debug);
        };
        var func = 'tool.post({\'url\':\''+link+'\',\'data\':\''+data+'\',\'onComplete\':'+complete+'});';
        tool.confirm(_lang.confirm, $(el).attr('title'), func);
    },
    valuelabels: function (){
        $('input.valuelabel,textarea.valuelabel')
        .attr('data-label',$(this).val())
        .bind({
            'focus':function(){
                tool.valuelabel($(this));
            },
            'blur':function(){
                tool.valuelabel($(this));
            }
        });
    },
    valuelabel: function (el){
        if(el.val() && el.val() == el.attr('data-label')){
            el.val('').removeClass('valuelabel');
        } else if(!el.val()) {
            el.val(el.attr('data-label')).addClass('valuelabel');
        }
    },
    marker: function(el){
        $(el).focus();
        $(el).parent().addClass('marked');
    },
    bubble: function(content, delay){
        delay = 1000 | delay;
        $('<div>',{
            'class':'bubble'
        })
        .html(content)
        .append($('<div>',{
            'class':'close'
        }).html('X')
            .click(function(){
                $(this).parent().remove()
            }))
        .append($('<div>',{
            'class':'clear'
        }))
        .hide().appendTo('#bubbles').fadeIn()
        .delay(delay).fadeOut();
        return 0;
    },
    pop: function(content){
        $('#result').removeAttr('class');
        $('#result').html('<div class="pop rounded">'
            +'<div class="container">'+ content +'<div class="clear"></div>'
            +'</div></div>');
        $(document).bind('keydown',function(e){
            if(e.keyCode == 27){ // esc
                $('#result').empty();
                $(document).unbind();
            }
        });

        //console.log(((window.innerHeight - $('result').getSize().y)*.5 + window.pageYOffset)+'px', window.innerHeight, window.pageYOffset);
        //$('result').css('top',((window.innerHeight - $('result').getSize().y)*.5 + window.pageYOffset));
        return 0;
    },
    result: function(code, status, message, fields, redirect, debug){
        code = code ? code : 800
        //$('result').attr('class','');
        if($('#submit')) $('#submit').attr('disabled','');
        if($('#loader')) $('#loader').css('display','none');
        /*if(fields) fields.each(function(el){
            $('#'+el).focus();
            $('#'+el).parent().parent().addClass('marked');
        });*/
        var content = '<h1>'+ status +'</h1><p>'+ message +'</p>'
        +(debug?'<p class="debug">'+ debug +'</p><div class="clear"></div>':'')
        +'<div class="close" onclick="$(\'#result\').html(\'\');">'+_lang.close+'</div>';
        this.pop(content);
        $('#result').addClass(code>=400 ? (code>=600 ? 'error' : 'alert') : 'success');
        if(redirect) location.href = redirect;
        return 0;
    //if(code < 600) setTimeout('if($(\'result\').getFirst())$(\'result\').getFirst().fade(0);',2000);
    },
    confirm: function(header, msg, func){
        var content = '<h1>'+ header +'</h1><p>'+ msg +'</p>'
        +'<div class="approve" onclick="$(\'#result\').html(\'\'); '+func+';">'+_lang.ok+'</div>'
        +'<div class="cancel" onclick="$(\'#result\').html(\'\');">'+_lang.cancel+'</div>'
        +'';
        $(document).bind('keydown',function(e){
            if(e.keyCode == 32){ // space
                eval(func);
                $('#result').empty();
                $(document).unbind();
            }
        });
        this.pop(content);
        $('#result').removeAttr('class').addClass('alert');
    },
    sortable: function(ID, handle, a){
        $(function() {
            $('#'+ID).sortable({
                handle: handle || 'img',
                forcePlaceholderSize: true,
                placeholder: 'ui-state-highlight',
                update: function(e, ui) {
                    var order = $(this).sortable('toArray').toString();
                    a.data = (a.data || '') +'&order='+ order
                    if(a.url) tool.post(a); else a.onComplete(order);
                }
            });
            $('#'+ID).disableSelection();
        });
    },
    inlineedit: function(el){
        var eventfunc = function(el, input, e){
            if((!e || e.keyCode == 13) && input.data('html') != input.val()) { // enter
                if(e) e.preventDefault();
                tool.post({
                    'url':input.data('url'),
                    'data':'ID='+input.data('id')+'&value='+input.val(),
                    'onComplete':function(r){
                        el.html(r.message.value).show();
                        input.remove();
                    }
                });
            } else if(!e || e.keyCode == 13 || e.keyCode == 27){ //esc
                if(e) e.preventDefault();
                el.html(input.data('html')).show();
                input.remove();
            }
        };
        el.bind({
            'click':function(){
                var input = $('<input>',{
                    'type':'text',
                    'class':'inlineedit',
                    'data-id':el.data('id'),
                    'data-url':el.data('url'),
                    'data-html':el.html()
                }).val(el.html())
                .bind({
                    'keydown':function(e){
                        return eventfunc(el, input, e);
                    },
                    'blur':function(){
                        return eventfunc(el, input);
                    }
                });
                el.hide().after(input.css({
                    'width':el.css('width'),
                    'height':el.css('height'),
                    'padding':el.css('padding'),
                    'font-size':el.css('font-size'),
                    'border':'0',
                    'background':'#faffcc'
                }));
                input.focus();
            }
        });
    },
    inlineedits: function(){
        $('.inlineedit').each(function(){
            tool.inlineedit($(this));
        });
    },
    spammasks: function(){
    //var pattern = /(([_.0-9a-z-]+)[ ]?\[at][ ]?(([0-9a-z][0-9a-z-]+.)\.[a-z]{2,4}))/g;
    //$('page').set('html',$('page').get('html').replace(pattern, '<a href="mailto:$2@$3">$2@$3</a>'));
    },
    checkbox: function(item){
        if($('#'+item.attr('title')).val() > 0){
            $('#'+item.attr('title')).val(0);
            item.removeClass('checked');
        } else {
            $('#'+item.attr('title')).val(1);
            item.addClass('checked');
        }
    },
    tabs: function (){
        $('.tabsMenu a').click(function(){
            $('.tabs .selected').removeClass('selected')
            $(this).addClass('selected');
            $('#'+$(this).attr('name')).addClass('selected');
        });
    },
    birthdate: function(start,finish,date){
        var bd = date.split('-',3);
        for(i=start;i>=finish;i--)
            $('<option>',{
                'selected':(bd[0]==i)
            }).val(i).html(i).appendTo('#year');
        for(i=1;i<=12;i++)
            $('<option>',{
                'selected':(bd[1]==i)
            }).val(i).html(i).appendTo('#month');
        for(i=1;i<=31;i++)
            $('<option>',{
                'selected':(bd[2]==i)
            }).val(i).html(i).appendTo('#day');
        tool.setday('year','month','day');
    },
    setday: function(year,month,day){
        var lastday = $('#'+day+' :last-child').val();
        var y = $('#'+year).val();
        y = (y)%4;
        var m = $('#'+month).val();
        var d;
        if(m == 1 || m == 3 || m == 5 || m == 7 || m == 8  || m == 10 || m == 12) d = 31;
        else if(m == 2) d = ( y == 0)?29:28;
        else if(lastday == 31) d = 30;
        if(lastday > d)
            for(i=lastday;i>d;i--) $('#'+day+' :last-child').remove();
        else if( lastday != d){
            lastday++;
            for(i=lastday;i<=d;++i)
                $('<option>').val(i).html(i).appendTo('#day');
        }
    },
    countries: function(url,item,selected) {
        tool.post({
            'url':url,
            'onComplete':function(r){
                if(r.countries){
                    $.each(r.countries, function(code, name){
                        $('<option>',{
                            'selected':(selected==code)
                        }).val(code).html(name).appendTo('#'+item);
                    });
                }
            }
        });
    },
    regions: function (url,item,selected) {
        $('#'+item).empty();
        $('<option>').val('').html('loading ...').appendTo(item);
        tool.post({
            'url':url,
            'onComplete':function(r){
                if(r.regions){
                    $('#'+item).empty();
                    $.each(r.regions, function(code, name){
                        $('<option>',{
                            'selected':(selected==code)
                        }).val(code).html(name).appendTo('#'+item);
                    });
                }
            }
        });
    },
    newCaptcha: function() {
        $('#captchaImg').attr('src','/captcha.png?'+Math.random());
    },
    listener: function(url){
        tool.listenerURL =  url ? url : tool.listenerURL;
        $('#listener').load(tool.listenerURL);
        /*
         $.ajax({
            url: tool.listenerURL,
            type: 'post',
            data: '',
            dataType: 'json',
            success: function(r){
                if(r.chat)
                tool.pop('<a href="/en/chat/room/'+r.chat.room+'">you have a chat request, click here to answer</a>');
            }
        });*/
        setTimeout("tool.listener()",15000);
    }
};
$(document).ready(function(){
    tool.linkposts();    
});
